<script setup>
import { onMounted } from "vue";
import { reqGetUserList, reqChangeStatus, reqDeleteUser,reqUpdateUser,reqGetUserInfo,reqAddUser} from "@/api/user";
import { ElMessage, ElMessageBox } from "element-plus";

import { ref ,reactive } from "vue";
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from "@element-plus/icons-vue";
import { useUserStore } from '@/stores/modules/user';
const userStore = useUserStore() 
// import { pa } from "element-plus/es/locale";

const userList = ref([]);
const page = ref({
  pageNum: 1,
  pageSize: 4,
});
const total = ref(0)
async function GetUserListByPage(){
  let res = await reqGetUserList(page.value.pageNum, page.value.pageSize);

  if (res.code === 200) {
    userList.value = res.data.userList;
    total.value = res.data.total;//wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
  } else {
    ElMessage.error(res.massage);
  }
}

onMounted(async () => {
  GetUserListByPage()
});
async function handleStatusChange(userId, status) {
  let res = await reqChangeStatus(userId, status);
  if (res.code === 200) {
    ElMessage.success("修改成功");
  } else {
    ElMessage.error(res.massage);
  }
}
function handleSizeChange(){
  GetUserListByPage()
}
function handleCurrentChange(){
  GetUserListByPage()
}
const open = async (userId) => {
  try {
    // 等待用户对确认框的操作
    await ElMessageBox.confirm(
      '该过程不可逆?',
      '您真的要删除吗',
      {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }
    );

    // 如果用户点击了确认按钮，执行下面的代码
    let res = await reqDeleteUser(userId);
    if (res.code === 200) {
      ElMessage.success("删除成功");
      GetUserListByPage(); // 刷新用户列表
    } else {
      ElMessage.error(res.message || "删除失败");
    }
  } catch (action) {
    // 如果用户点击了取消按钮或关闭了消息框，catch 块会被触发
    ElMessage({
      type: 'info',
      message: '取消删除'
    });
  }
};

const drawer = ref(false)
const currentRow = ref(null);

// 添加编辑处理函数
const handleEdit = (row) => {
  
  currentRow.value = { ...row };
  drawer.value = true;
};
// 保存编辑后的数据
const saveEdit = async () => {
  if (!currentRow.value) return;

  try {
    // 直接传递 currentRow 对象给 reqUpdateUser
    await reqUpdateUser(currentRow.value);
    
    ElMessage.success("更新成功");

    // 如果是当前登录用户，则刷新用户信息
    if (currentRow.value.userId === userStore.userInfo.userId) {
      let res = await reqGetUserInfo();
      if (res.code === 200) {
        userStore.setUserInfo(res.data);
      } else {
        ElMessage.error("刷新用户信息失败");
      }
    } GetUserListByPage();

    // 关闭抽屉
    drawer.value = false;
  } catch (error) {
    ElMessage.error("更新失败");
    console.error(error);
  }
};
// 取消编辑
const cancelEdit = () => {
  drawer.value = false;
  // 重置 currentRow 为 null 或者重新获取原始数据
  currentRow.value = null;
};
const addDrawer = ref(false);
const newUser = reactive({
  userName: '',
  nickName: '',
  phonenumber: '',
  email: '',
  avatar: '', // 如果需要处理文件上传，这里可能需要调整
});

// 打开添加用户的抽屉
const handleAdd = () => {
  // 清空 newUser 对象中的数据
  Object.keys(newUser).forEach(key => {
    newUser[key] = '';
  });
  addDrawer.value = true;
};

// 处理头像上传
const handleAvatarUpload = (event) => {
  const file = event.target.files[0];
  if (file) {
    // 可以在这里进行文件验证、预览等操作
    // 假设服务器接受 base64 编码的图片字符串
    const reader = new FileReader();
    reader.onloadend = () => {
      newUser.avatar = reader.result;
    };
    reader.readAsDataURL(file);
  }
};

// 保存新用户
const saveNewUser = async () => {
  try {
    await reqAddUser(newUser);
    ElMessage.success("添加成功");
    GetUserListByPage(); // 刷新用户列表
    addDrawer.value = false; // 关闭抽屉
  } catch (error) {
    ElMessage.error("添加失败");
    console.error(error);
  }
};

// 取消添加
const cancelAdd = () => {
  addDrawer.value = false;
};
</script>
<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>用户管理</span>
        <el-button class="button" type="primary"  @click="handleAdd" >添加用户</el-button>
      </div>
    </template>
    <el-drawer v-model="drawer" title="编辑用户信息" :with-header="true">
  <div v-if="currentRow">
    <!-- 表单开始 -->
    <el-form label-width="80px">
      <el-form-item label="用户编号" prop="userId">
        <el-input v-model="currentRow.userId" disabled></el-input> <!-- 用户编号通常不可编辑 -->
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="currentRow.userName"></el-input>
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="currentRow.nickName"></el-input>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="currentRow.phonenumber"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="currentRow.email"></el-input>
      </el-form-item>
      <el-form-item label="头像">
       <!--  <img :src="currentRow.avatar" alt="头像" style="height: 60px" /> -->
       <el-input v-model="currentRow.avatar"></el-input>
        <!-- 如果需要上传新头像，这里可以添加文件上传组件 -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveEdit">保存</el-button>
        <el-button @click="cancelEdit">取消</el-button>
      </el-form-item>
    </el-form>
    <!-- 表单结束 -->
  </div>
</el-drawer>
<!-- 在 el-card 内部，紧接在编辑用户信息的 drawer 下方 -->
<el-drawer v-model="addDrawer" title="添加用户信息" :with-header="true">
  <div>
    <!-- 表单开始 -->
    <el-form label-width="80px" :model="newUser">
      <el-form-item label="用户名">
        <el-input v-model="newUser.userName"></el-input>
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="newUser.nickName"></el-input>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="newUser.phonenumber"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="newUser.email"></el-input>
      </el-form-item>
      <el-form-item label="头像">
        <!-- 上传头像 -->
     <!--    <input type="file" @change="handleAvatarUpload" /> -->
        <el-input v-model="newUser.avatar"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveNewUser">保存</el-button>
        <el-button @click="cancelAdd">取消</el-button>
      </el-form-item>
    </el-form>
    <!-- 表单结束 -->
  </div>
</el-drawer>
    <el-table :data="userList" border style="width: 100%">
      <el-table-column prop="userId" label="用户编号" width="120" />
      <el-table-column prop="userName" label="用户名" width="180" />
      <el-table-column prop="nickName" label="昵称" width="180" />
      <el-table-column prop="phonenumber" label="电话" width="180" />
      <el-table-column prop="email" label="邮箱" width="180" />
      <el-table-column label="头像" width="100">
        <template #default="scope">
          <img :src="scope.row.avatar" style="height: 60px" />

        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="scope">

          <el-switch
            @change="handleStatusChange(scope.row.userId, scope.row.status)"
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            class="ml-2"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        
        <template #default="scope">
          <el-button  type="primary" :icon="Edit" circle  @click="() => handleEdit(scope.row)" />
          <el-button type="danger" :icon="Delete" circle @click="() => {  open(scope.row.userId); }" />
        
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
     
      <el-pagination
        v-model:current-page="page.pageNum"
        v-model:page-size="page.pageSize"
        :page-sizes="[1, 2, 3, 4, 5]"
        :small="false"
        :size="size"
        :disabled="false"
        :background="false"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
  </el-card>
 
</template>
  
  <style>
  .el-pagination{
      margin-top: 20px;
  }
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}


.el-table .cell {
  text-align: center;
}


.el-table th > .cell {
  text-align: center; 
}
.demo-pagination-block {
  display: flex;
  justify-content: center;  
  margin-top: 20px;        
}
</style>
  